package com.eduhzy.ttw.clazz.mvp.presenter;

import android.app.Application;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.clazz.mvp.contract.ClazzReportContract;
import com.eduhzy.ttw.clazz.mvp.model.entity.ClazzReportHead;
import com.eduhzy.ttw.clazz.mvp.model.entity.ClazzReportList;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.commonsdk.holder.AutoBaseViewHolder;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


/**
 * @author xubo
 * @date 2018-12-7 10:35:33
 */
@ActivityScope
public class ClazzReportPresenter extends BasePresenter<ClazzReportContract.Model, ClazzReportContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    private int page = 1;
    private int pageSize = 10;
    @Inject
    BaseQuickAdapter<ClazzReportList, AutoBaseViewHolder> mAdapter;

    @Inject
    public ClazzReportPresenter(ClazzReportContract.Model model, ClazzReportContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }


    public void getClassData(boolean pullToRefresh, int classId, long date, int type) {
        if (pullToRefresh) {
            page = 1;
        } else {
            page++;
        }

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("classId", classId);
        map.put("teacherId", SPUtils.getInstance().getString(Constants.USERID));
        map.put("date", date);
        map.put("type", type);
        map.put("pageNo", page);
        map.put("pageSize", pageSize);
        Observable<CommonData<List<ClazzReportList>>> observable = null;
        if (pullToRefresh) {
            observable = mModel.getClassData(map)
                    .flatMap((Function<CommonData<ClazzReportHead>,
                            Observable<CommonData<List<ClazzReportList>>>>)
                            clazzReportHeadCommonData -> {
                                if (clazzReportHeadCommonData.isResult()) {
                                    mRootView.updateHead(clazzReportHeadCommonData.getData());
                                    return mModel.getScoreRecordList(map);
                                } else {
                                    return Observable.error(new NullPointerException(clazzReportHeadCommonData.getMessage()));
                                }
                            }
                    );
        } else {
            observable = mModel.getScoreRecordList(map);
        }
        observable
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    if (pullToRefresh)
                        mRootView.showLoading();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    if (pullToRefresh)
                        mRootView.hideLoading();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<List<ClazzReportList>>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<List<ClazzReportList>> commonData) {
                        if (commonData.isResult()) {
                            if (pullToRefresh) {
                                mAdapter.setNewData(commonData.getData());
                            } else {
                                mAdapter.addData(commonData.getData());
                            }
                            if (ObjectUtils.isNotEmpty(commonData.getData()) && commonData.getData().size() < pageSize) {
                                mAdapter.loadMoreEnd(true);
                            } else {
                                mAdapter.loadMoreComplete();
                            }
                        } else {
                            mRootView.showMessage(commonData.getMessage());
                        }
                        if (mAdapter.getEmptyViewCount() <= 0) {
                            mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.no_data));
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        if (t instanceof ConnectException || t instanceof UnknownHostException) {
                            mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.no_network));
                        } else if (t instanceof NullPointerException) {
                            mRootView.showMessage(t.getMessage());
                        } else {
                            mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.load_error));
                        }
                    }
                });
    }
}
